package main

import (
	"bufio"
	"bytes"
	"compress/gzip"
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/go-playground/validator/v10"
	"github.com/golang-jwt/jwt/v4"
	"github.com/joho/godotenv"
	"github.com/robfig/cron"
	"go.uber.org/zap"
	"go/ast"
	"golang.org/x/exp/constraints"
	"golang.org/x/sync/errgroup"
	"golang.org/x/sync/singleflight"
	"golang.org/x/time/rate"
	"io"
	"io/ioutil"
	"math"
	"math/rand"
	"net/rpc"
	"net/url"
	"os/exec"
	"path"
	"regexp"
	"runtime"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/gocolly/colly"
	"github.com/gocolly/colly/extensions"

	"log"
	"net"
	"net/http"
	"os"
	"reflect"
	"sort"
	"strings"
	"sync"
	"sync/atomic"
	"time"
	"unicode"

	"github.com/spf13/viper"
)

func main() {
	demo81()
}

type TokenBucket struct {
	tokens   chan struct{}
	rate     int
	stopChan chan struct{}
}

func NewTokenBucket(rate int) *TokenBucket {
	tb := &TokenBucket{
		tokens:   make(chan struct{}, rate),
		rate:     rate,
		stopChan: make(chan struct{}),
	}
	go func() {
		ticker := time.NewTicker(time.Second / time.Duration(rate))
		defer ticker.Stop()
		for {
			select {
			case <-ticker.C:
				tb.tokens <- struct{}{}
			case <-tb.stopChan:
				return
			}
		}
	}()
	return tb
}

func (tb *TokenBucket) Take() {
	<-tb.tokens
}
func (tb *TokenBucket) Stop() {
	tb.stopChan <- struct{}{}
}

func demo81() {
	tb := NewTokenBucket(5)
	defer tb.Stop()
	var wg sync.WaitGroup
	log.Println("所有请求开始处理...")
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func(idx int) {
			defer wg.Done()
			resp, err := http.Get("https://httpbin.org/get")
			if err != nil {
				log.Printf("请求 %d 失败：%v\n", idx, err)
				return
			}
			defer resp.Body.Close()

			log.Printf("请求 %d 成功，状态码：%d\n", idx, resp.StatusCode)
		}(i)
	}
	wg.Wait()
	log.Println("所有请求处理完成")
}

func demo80() {
	duration := time.Second / 10
	log.Println("duration => ", duration)
}

func demo79() {
	client := &http.Client{}
	req, _ := http.NewRequest("GET", "http://httpbin.org/get", nil)
	req.Header.Add("name", "zhaofan")
	req.Header.Add("age", "3")
	resp, _ := client.Do(req)
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
}

func demo78() {

	limiter := rate.NewLimiter(rate.Limit(10), 5)
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func(idx int) {
			defer wg.Done()
			if err := limiter.Wait(context.Background()); err != nil {
				log.Printf("请求 %d 获取令牌失败 :%v\n", idx, err)
				return
			}
			// 4. 发送HTTP请求
			resp, err := http.Get("https://httpbin.org/get")
			if err != nil {
				log.Printf("请求 %d 失败：%v\n", idx, err)
				return
			}
			defer resp.Body.Close()

			log.Printf("请求 %d 成功，状态码：%d\n", idx, resp.StatusCode)
		}(i)
	}
	wg.Wait()
	log.Println("所有请求处理完成")
}

func demo76() {
	params := url.Values{}
	params.Set("name", "zhaofan")
	params.Set("age", "18")
	url, err := url.Parse("http://httpbin.org/get")
	if err != nil {
		panic(err)
	}
	url.RawQuery = params.Encode()
	urlPath := url.String()
	fmt.Println(urlPath)
	resp, err := http.Get(urlPath)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(body))

}

func demo75() {
	resp, err := http.Get("http://httpbin.org/get?name=zhaofan&age=23")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	all, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(all))

}

type MyCustomClaims struct {
	Foo string `json:"foo"`
	jwt.StandardClaims
}

func create() {
	//mySigningKey := []byte("AllYourBase")
	// Create the Claims
	claims := MyCustomClaims{
		"bar",
		jwt.StandardClaims{
			ExpiresAt: 15000,
			Issuer:    "test",
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	//ss, err := token.SignedString(mySigningKey)
	fmt.Printf("%v %v", token)
}

func signature() {
	tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c"
	type MyCustomClaims struct {
		Foo string `json:"foo"`
		jwt.StandardClaims
	}

	// sample token is expired.  override time so it parses as valid
	token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		// 只返回加密的秘钥
		return []byte("AllYourBase"), nil
	})

	if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
		fmt.Printf("%v %v", claims.Foo, claims.StandardClaims.ExpiresAt)
	} else {
		fmt.Println(err)
	}
}

func demo77() {
	create()
	signature()
}

func Max[T constraints.Ordered](slice []T) T {
	if len(slice) == 0 {
		var zero T
		return zero
	}
	maxV := slice[0]
	for _, v := range slice {
		if v > maxV {
			maxV = v
		}
	}
	return maxV
}

func demo74() {
	var g errgroup.Group
	g.SetLimit(2)
	for i := 0; i < 3; i++ {
		id := i
		g.Go(func() error {
			fmt.Printf("Goroutine %d is running...\n", id)
			return errors.New("get error from id  " + strconv.Itoa(id))
		})
	}
	if err := g.Wait(); err != nil {
		fmt.Println("err:", err)
	} else {
		fmt.Println("all goroutine is done")
	}
}

func demo73() {
	err := godotenv.Load(".env")
	if err != nil {
		log.Fatal("Error loading ..env file")
	}
	A := os.Getenv("A")
	fmt.Println(A)
}

func demo72() {
	var wg sync.WaitGroup
	n := 5
	chs := make([]chan struct{}, n)
	for i, _ := range chs {
		chs[i] = make(chan struct{})
	}
	char := 'A'
	for i := 0; i < n; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			for {
				_, ok := <-chs[i]
				if !ok {
					return
				}
				if char > 'Z' {
					for _, ch := range chs {
						close(ch)
					}
					return
				}
				fmt.Printf("go程 %d 打印 %c\n", i, char)
				char++
				chs[(i+1)%n] <- struct{}{}
			}
		}(i)
	}
	chs[0] <- struct{}{}
	wg.Wait()
}

func demo71() {
	chNum := make(chan struct{})
	chChar := make(chan struct{})
	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		chNum <- struct{}{}
	}()
	go func() {
		defer wg.Done()
		printNum(chNum, chChar, 1)
	}()

	go func() {
		defer wg.Done()
		printChar(chNum, chChar, 1)
	}()
	wg.Wait()
}
func printChar(chNum, chChar chan struct{}, count int) {
	i := 'A'
	for {
		<-chChar
		if i > 'Z' {
			close(chNum)
			return
		}
		for j := 0; j < count; j++ {
			fmt.Print(string(i))
			i++
		}
		chNum <- struct{}{}
	}
}
func printNum(chNum, chChar chan struct{}, count int) {
	i := 1
	for {
		_, ok := <-chNum
		if !ok {
			return
		}
		for j := 0; j < count; j++ {
			fmt.Print(i)
			i++
		}
		chChar <- struct{}{}
	}
}

type U1 struct {
	Name string `geeorm:"name" json:"name" binding:"required"`
	Age  int    `geeorm:"age" json:"age" binding:"required"`
}

func demo70() {
	mp := sync.Map{}
	mp.Store("k", "v")
	value, ok := mp.Load("k")
	if ok {
		fmt.Println(value)
	}
	fmt.Println(time.Now().Format(time.DateTime))

	u1Type := reflect.TypeOf(U1{})

	for i := 0; i < u1Type.NumField(); i++ {
		field := u1Type.Field(1)
		if !field.Anonymous && ast.IsExported(field.Name) {
			log.Println(field.Name, "是公开可导出的")
			if value, ok := field.Tag.Lookup("geeorm"); ok {
				log.Println(value)
			}
		}

	}
}
func demo69() {
	s := "abcd"
	fmt.Printf("%x\n", []byte(s))
}

func demo68() {
	s := "我喜欢golang"
	runes := []rune(s)
	log.Println(string(runes))
	log.Println(len(runes))
}

func demo67() {
	const numJobs = 5
	jobs := make(chan int, numJobs)
	const maxConcurrent = 2
	sem := make(chan struct{}, maxConcurrent)
	var wg sync.WaitGroup
	wg.Add(1)
	for w := 1; w <= maxConcurrent; w++ {
		//wg.Add(1)
		go func(id int) {
			for {
				sem <- struct{}{}
				job, ok := <-jobs
				if !ok {
					<-sem // 释放信号
					fmt.Printf("Worker %d 结束运行\n", id)
					break
				}
				fmt.Printf("Worker %d started job %d\n", id, job)
				// 模拟工作
				fmt.Printf("Worker %d finished job %d\n", id, job)
				<-sem // 释放信号
			}
			//select {}
			//wg.Done()
		}(w)
	}
	// 发送工作任务
	for j := 1; j <= numJobs; j++ {
		jobs <- j
	}
	close(jobs)

	// 等待所有工作完成
	wg.Wait()
	//select {}
}

func worker3(id int, jobs <-chan int) {
	for j := range jobs {
		fmt.Printf("Worker %d started job %d\n", id, j)
		// 模拟工作
		fmt.Printf("Worker %d finished job %d\n", id, j)
	}
}

func createObject() *int {
	num := 10
	return &num
}
func demo66() {
	var memStats runtime.MemStats
	runtime.ReadMemStats(&memStats)
	fmt.Printf("Before creating object: Allocated memory = %d bytes\n", memStats.Alloc)

	obj := createObject()
	runtime.ReadMemStats(&memStats)
	fmt.Printf("After creating object: Allocated memory = %d bytes\n", memStats.Alloc)
	fmt.Println(*obj)
	obj = nil    // 使对象成为不可达对象
	runtime.GC() // 手动触发垃圾回收
	runtime.ReadMemStats(&memStats)
	fmt.Printf("After garbage collection: Allocated memory = %d bytes\n", memStats.Alloc)

	time.Sleep(1 * time.Second)
}

func demo65() {
	path1 := path.Dir("./doc/b/aa.txt")
	fmt.Println(path1)
	stat, _ := os.Stat(".")
	fmt.Println(stat.Name())
}
func demo64() {
	filePath := "D://data1.txt"
	stat, err := os.Stat(filePath)
	if err != nil && os.IsNotExist(err) {
		log.Fatal("文件不存在")
	}
	println(stat.Name())
}

func demo63() {
	var buf bytes.Buffer
	buf.Write([]byte("Hello World"))
	fmt.Println(buf.String())
	buf.WriteString(",Good")
	fmt.Println(buf.String())
	byteArr := buf.Bytes()
	fmt.Println(string(byteArr))
	buf.Reset()
	fmt.Println(buf.Len())
	fmt.Println("last buf => ", buf.String())
}

func demo62() {
	file, err := os.Open("D://data.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()
	n, _ := io.Copy(os.Stdout, file)
	log.Println(" 一共读取了 ", n, "个字节")

}
func demo61() {
	_, _ = div(10, 0)

}

func div(a, b int) (res int, err error) {
	defer func() {
		if err := recover(); err != nil {
			err = fmt.Errorf("panic occurred: %v", err)

		}
	}()
	if b == 0 {
		panic("division by zero")
	}
	return a / b, nil
}

func demo60() {
	var g singleflight.Group
	var wg sync.WaitGroup
	keys := []string{"k1", "k1", "k2", "k2"}
	for _, key := range keys {
		wg.Add(1)
		go func(key string) {
			defer wg.Done()
			result, _, shared := g.Do(key, func() (interface{}, error) {
				return fetchData(key)
			})
			if shared {
				fmt.Printf("Result for key %s was shared among multiple requests\n", key)
			} else {
				fmt.Printf("Result for key %s was fetched independently\n", key)
			}
			fmt.Printf("Result for key %s: %s\n", key, result)
		}(key)
	}
	wg.Wait()
}

func fetchData(key string) (string, error) {
	fmt.Printf("Fetching data fro key:%s\n", key)
	time.Sleep(2 * time.Second)
	return fmt.Sprintf("Data for %s", key), nil
}

func PrintSlice[T any](s []T) {
	for _, v := range s {
		typ := reflect.TypeOf(v)
		fmt.Println(typ.String())
		_, _ = fmt.Fprintf(os.Stdout, "%T   %v \n", v, v)
	}
}
func demo59() {
	intSlice := []int{1, 2, 3}
	stringSlice := []string{"a", "b", "c"}

	PrintSlice(intSlice)
	PrintSlice(stringSlice)

}

type P1 struct {
	Name string
	Age  int
}

func demo58() {
	p1 := P1{Age: 10, Name: "yzp"}
	obj1 := reflect.TypeOf(p1)
	obj2 := reflect.ValueOf(p1)
	for i := 0; i < obj1.NumField(); i++ {
		field := obj1.Field(i)
		value := obj2.Field(i).Interface()
		fmt.Println(field.Name, "=>", value)
	}
}

var pool = sync.Pool{
	New: func() interface{} {
		return bytes.NewBuffer(make([]byte, 0, 1024))
	},
}

func GetBuf() *bytes.Buffer {
	return pool.Get().(*bytes.Buffer)
}
func PutBuf(buf *bytes.Buffer) {
	buf.Reset()
	pool.Put(buf)
}
func demo57() {
	fmt.Println(os.Getpid())
	fmt.Println(runtime.GOOS)
}

type MyJob struct {
}

func (job *MyJob) Run() {
	log.Println("MyJob run...")
}

func runJob2() {
	c := cron.New()
	err := c.AddFunc("* * * * *", func() {
		log.Println("now run func !!!")
	})
	if err != nil {
		panic(err)
	}
	c.Start()
	select {}
}
func runJob() {
	c := cron.New()
	c2 := make(chan struct{})
	spec := "* * * * *"
	job := &MyJob{}
	err := c.AddJob(spec, job)

	if err != nil {
		log.Fatal("add job err: ", err)
		return
	}
	fmt.Printf("任务添加成功，任务 ID: %d\n", job)

	// 启动定时任务调度器
	c.Start()

	// 让程序保持运行
	//select {}
	//<-c2
	c2 <- struct{}{}
}

func demo56() {
	runJob2()

}

func demo55() {
	var i int = 90
	log.Println(strconv.Itoa(i))
}

func demo54() {

	a2 := A2{A1{name: "yzp", age: 21}}
	log.Println(a2.name)
	log.Println(a2.age)
	log.Println(a2.A1.age)
	log.Println(a2.A1.name)
}

type A1 struct {
	name string
	age  int
}

type A2 struct {
	A1
}

func demo53_RPC() {
	arith := new(Arith)
	rpc.Register(arith)
	listen, err := net.Listen("tcp", ":1234")
	log.Println("listen : ", listen.Addr().String())
	if err != nil {
		log.Fatal("Listen TCP error: ", err)
	}
	for {
		conn, err := listen.Accept()
		if err != nil {
			log.Fatal("Accept error: ", err)
		}

		rpc.ServeConn(conn)
	}
}

type Arith struct {
}
type Args struct {
	A, B int
}

func (a *Arith) Multiply(args *Args, reply *int) error {
	*reply = args.B * args.A
	return nil
}

func demo52() {
	logger, _ := zap.NewProduction()
	defer func(logger *zap.Logger) {
		err := logger.Sync()
		if err != nil {

		}
	}(logger)
	logger.Debug("debu msg")
	log.Println("println msg")
	logger.Info("this is info msg")
	logger.Error("error ")

}

func demo51() {
	fmt.Println([]struct {
		name string
		age  int32
	}{{
		name: "yzp", age: 12,
	}, {name: "Bob", age: 13}})
	fmt.Println([]byte("aa"))
	fmt.Println([]byte{})
}

func demo50() {
	compressor := GzipCompressor{}
	s := "i love china"
	zip, _ := compressor.Zip([]byte(s))
	fmt.Println("zip data => ", zip, len(zip))
	unzip, _ := compressor.Unzip(zip)
	fmt.Println("unzip data=> ", string(unzip), len(unzip))

}

type GzipCompressor struct {
}

func (g *GzipCompressor) Zip(data []byte) ([]byte, error) {
	buf := bytes.NewBuffer(nil)
	writer := gzip.NewWriter(buf)
	defer writer.Close()
	_, err := writer.Write(data)
	if err != nil {
		return nil, err
	}
	err = writer.Flush()
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), err
}
func (g *GzipCompressor) Unzip(data []byte) ([]byte, error) {
	reader, err := gzip.NewReader(bytes.NewBuffer(data))
	if err != nil {
		return nil, err
	}
	defer reader.Close()
	data, err = ioutil.ReadAll(reader)
	if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
		return nil, err
	}
	return data, err
}

type Compressor interface {
	Zip([]byte) ([]byte, error)
	Unzip([]byte) ([]byte, error)
}

func demo49() {
	var impl = &ABImpl{}
	var _ AB = (*ABImpl)(nil)
	//if _, ok := impl.(AB); !ok {
	//	panic("接口没有实现")
	//
	//}
	impl.sayHi()
}

type ABC interface {
	sayHello()
}
type AB interface {
	sayHi()
}
type ABImpl struct {
}

func (a *ABImpl) sayHi() {
	fmt.Println("say hi")
}

func minimumOperations(nums []int) int {
	ans := 0
	for _, x := range nums {
		if x%3 != 0 {
			ans++
		}
	}
	return ans
}

func addedInteger(nums1 []int, nums2 []int) int {
	n := len(nums1)
	return (sumArr(nums2) - sumArr(nums1)) / n
}
func sumArr(arr []int) int {
	sum := 0
	for _, val := range arr {
		sum += val
	}
	return sum
}

func countTestedDevices(batteryPercentages []int) int {
	n := len(batteryPercentages)
	need := 0
	for i := 0; i < n; i++ {
		if batteryPercentages[i] > 0 {
			need++
			for j := i + 1; j < n; j++ {
				batteryPercentages[j] = max(0, batteryPercentages[j]-1)
			}
		}
	}
	return need
}

func sumOfEncryptedInt(nums []int) int {
	ans := 0
	for _, x := range nums {
		mx, base := 0, 0
		for ; x > 0; x /= 10 {
			mx = max(mx, x%10)
			base = base*10 + 1
		}
		ans += mx * base
	}
	return ans
}

func clearDigits(s string) string {
	var res []byte
	for _, c := range s {
		if unicode.IsDigit(c) {
			res = res[:len(res)-1]
		} else {
			res = append(res, byte(c))
		}
	}
	return string(res)
}

func minimumChairs(s string) int {
	cur, ans := 0, 0
	for i := 0; i < len(s); i++ {
		if s[i] == 'E' {
			cur++
		} else if s[i] == 'L' {
			cur--
		}
		ans = max(ans, cur)
	}
	return ans
}
func canAliceWin(nums []int) bool {
	sort.Ints(nums)
	ans, sum := 0, 0
	for _, num := range nums {
		if num > 0 && num < 10 {
			ans += num
		}
		sum += num
	}
	return ans != sum/2

}
func minimumAverage(nums []int) float64 {

	sort.Ints(nums)
	res, n := math.MaxFloat64, len(nums)
	for i := 0; i < n/2; i++ {
		res = min(res, float64(nums[i]+nums[n-i-1])/2)
	}
	return res
}

func findPermutationDifference(s string, t string) int {
	char2idx := make(map[rune]int)
	for i, ch := range s {
		char2idx[ch] = i
	}
	ans := 0
	for i, ch := range t {
		if char2idx[ch] != i {
			ans = int(math.Abs(float64(i - char2idx[ch])))
		}
	}
	return ans
}

func minOperations(nums []int, k int) int {
	ans := 0
	for _, num := range nums {
		if num < k {
			ans++
		}
	}
	return ans
}

func stableMountains(height []int, threshold int) []int {
	ans := make([]int, 0)
	for i, _ := range height {
		if i > 0 && height[i-1] > threshold {
			ans = append(ans, i)
		}
	}
	return ans
}

func subarraySum(nums []int) int {
	s := make([]int, 0)
	for i, num := range nums {
		s[i+1] = s[i] + num
	}
	ans := 0
	for i, num := range nums {
		ans += s[i+1] - s[max(i-num, 0)]
	}
	return ans
}

func convertDateToBinary(date string) string {
	year, _ := strconv.Atoi(date[:4])
	month, _ := strconv.Atoi(date[5:7])
	day, _ := strconv.Atoi(date[8:])
	return binary(year) + binary(month) + binary(day)
}
func binary(x int) string {
	var s []byte
	for ; x != 0; x >>= 1 {
		s = append(s, '0'+byte(x&1))
	}
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
	return string(s)
}

func demo48() {
	err := fmt.Errorf("wrapped error:%w", io.EOF)
	if errors.Is(err, io.EOF) {
		fmt.Println("错误是 io.EOF 或是它的包装类型")
	}

	err = fmt.Errorf("wrapped error:%w", sql.ErrNoRows)

}
func demo47() {
	arr := make([]int, 1)
	arr[0] = 1
	err1 := MyErr{Codes: arr}
	if errors.Is(err1, MyErr{Codes: arr}) {
		fmt.Println("is equal")
	}
}

type MyErr struct {
	Codes []int
}

func (me MyErr) Error() string {
	return fmt.Sprintf("codes:%v", me.Codes)
}
func (me MyErr) Is(target error) bool {
	if me2, ok := target.(MyErr); ok {
		return reflect.DeepEqual(me, me2)
	}
	return false
}

func demo46() {
	err := fileChecker("not_here.txt")
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			fmt.Println("that file not exist")
		}
	}
}

func fileChecker(name string) error {
	f, err := os.Open(name)
	if err != nil {
		return fmt.Errorf("in fileChecker:%w", err)
	}
	f.Close()
	return nil
}

func demo45() {
	cmd := exec.Command("lsof", "-i", "9092")
	output, err := cmd.Output()
	if err != nil {
		fmt.Println("命令执行出错")
		return
	}
	fmt.Println(string(output))
}

func demo44() {
	s := struct {
		Name string `json:"name" `
		Age  int32  `json:"age"`
	}{Name: "yzp"}
	fmt.Printf("%#v\n", s)
	ps := &s
	value := reflect.ValueOf(ps)
	if value.CanAddr() {
		fmt.Println("可寻址")
	}
	if value.CanInterface() {
		fmt.Println("可获取实际值")
	}
	switch value.Kind() {
	case reflect.Ptr:
		fmt.Println("ptr value is:", value.Elem().Interface())
	case reflect.Struct:
		{
			fmt.Println("struct value is:", value.Elem().Interface())
			for i := 0; i < value.Elem().NumField(); i++ {
				field := value.Elem().Field(i)
				if !field.CanInterface() {
					continue
				}
				tag := value.Type().Field(i).Tag.Get("json")
				if tag == "" || tag == "-" || tag == "_" {
					continue
				} else {
					fmt.Println(tag)
				}

			}
		}

	default:
		fmt.Println("not know")
	}
}

type Foo int

func (f Foo) Bar() {
	fmt.Println(fmt.Sprintf("My receiver is %T %v\n", f, f))
}

func demo43() {
	a := Foo(42)
	a.Bar()
	b := Foo(43)
	Foo.Bar(b)
}

func producer(out chan<- int) {
	for i := 0; i < 5; i++ {
		out <- i
		fmt.Println("send  ", i)
	}
	close(out)
}
func consumer(in <-chan int, wg *sync.WaitGroup) {
	for val := range in {
		fmt.Println("received ", val)
		wg.Done()
	}
}
func demo42() {
	ch := make(chan int, 10)
	var wg sync.WaitGroup
	wg.Add(5)
	go producer(ch)
	go consumer(ch, &wg)
	fmt.Println("NumGoroutine:", runtime.NumGoroutine())

	wg.Wait()
}
func demo41() {
	type Person struct {
		Name string
		Age  int32
	}
	marshal, _ := json.Marshal(&Person{
		Name: "yzp", Age: 23,
	})
	log.Println(marshal)
	person := Person{}
	json.Unmarshal(marshal, &person)
	log.Println(person)

	res, _ := strconv.ParseInt("1", 10, 64)
	fmt.Printf("%#v\n", res)
	stat, _ := os.Stat("D:/北朝帝业.txt")
	log.Println(stat.Name())
	log.Println(stat.Size())
}

func demo40() {
	compile2 := regexp.MustCompile(`\s+`)
	s := "1284 不计前嫌"
	s = compile2.ReplaceAllString(s, "\n\t")
	fmt.Println(s)
}
func demo39() {
	compile := regexp.MustCompile(`[0-9]+`)
	s := "1284 不计前嫌"
	allString := compile.FindAllString(s, -1)
	fmt.Println(allString)
	fmt.Println("第" + allString[0] + "章 " + compile.ReplaceAllString(s, ""))

}

func colly_DingDian() {
	c1 := colly.NewCollector(colly.AllowedDomains("www.ddyueshu.cc"))
	c1.SetRequestTimeout(60 * time.Second)
	extensions.RandomUserAgent(c1)
	extensions.Referer(c1)

	c2 := c1.Clone()

	file, _ := os.OpenFile("D:/北朝帝业.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModeAppend|os.ModePerm)
	defer file.Close()
	writer := bufio.NewWriter(file)
	compile := regexp.MustCompile(`[0-9]+`)
	compile2 := regexp.MustCompile(`\s{2,+}`)
	c2.OnHTML("div[class=box_con]", func(e *colly.HTMLElement) {
		title := e.DOM.Find("div[class=bookname]>h1").Text()
		allString := compile.FindAllString(title, -1)
		if allString != nil {
			title = "第" + allString[0] + "章 " + compile.ReplaceAllString(title, "")
		}
		log.Println(title)

		content := e.DOM.Find("div[id=content]").Text()
		content = strings.Replace(content, "\n", "", -1)
		content = strings.Replace(content, "chaptererror();请记住本书首发域名：ddyueshu.cc。顶点小说手机版阅读网址：m.ddyueshu.cc", "", -1)
		content = compile2.ReplaceAllString(content, "\n\t")

		log.Println(content)

		writer.WriteString("\n" + title + "\n")
		writer.WriteString(content)
		writer.Flush()

		log.Println("===============================")
	})

	c1.OnHTML("dt:nth-of-type(2)~dd>a[href]", func(e *colly.HTMLElement) {
		href := e.Attr("href")
		if href == "" {
			return
		}

		url := e.Request.AbsoluteURL(href)
		c2.Visit(url)
	})
	c1.OnRequest(func(r *colly.Request) {
		if strings.HasSuffix(r.URL.String(), ".html") {
			fmt.Println("Visiting", r.URL.String())
		}

	})

	c1.Visit("https://www.ddyueshu.cc/68216_68216004/")
}

func demo38() {
	type Fruit struct {
		ID    int     `key:"id" json:"id"  `
		Name  string  `key:"name" json:"name"  `
		Price float64 `key:"price" json:"price"  `
	}

}

func printAll(val any) {
	value := reflect.ValueOf(val)
	switch value.Kind() {
	case reflect.Ptr:
		elem := value.Elem()
		if !elem.CanAddr() {
			return
		}
	case reflect.Struct:
		for i := 0; i < value.NumField(); i++ {
			field := value.Field(i)
			a := field.Interface()

			log.Println(a)
		}
	default:
		panic("unhandled default case")
	}
}

func demo37() {
	type Person struct {
		Name string
		Age  int32
	}
	person := &Person{Name: "yzp", Age: 18}
	reflect.ValueOf(person).Elem().Field(0).SetString("yyy")
	reflect.ValueOf(person).Elem().Field(1).SetInt(23)
	reflect.ValueOf(person).Elem().FieldByName("Age").SetInt(24)
	log.Println(person)

	person1 := &Person{Name: "yzp", Age: 18}
	person3 := Person{Name: "yzp", Age: 18}
	person2 := &Person{Name: "yzpppp", Age: 12}
	reflect.ValueOf(person2).Elem().Set(reflect.ValueOf(person1).Elem())
	log.Println(person2)
	printAll(person3)

}

func demo36() {
	var mapx sync.Map
	mapx.Store("a", 1)
	mapx.Store("b", 2)
	mapx.Store("c", 3)
	value, isFind := mapx.Load("d")
	if isFind == false {
		log.Println("没有该元素")
	} else {
		log.Println("存在该元素", value)
	}
	mapx.Range(func(k, val interface{}) bool {
		value1 := val.(int)
		log.Println(value1)
		return true
	})
}

func demo35() {
	ticker := time.NewTicker(1000 * time.Millisecond)
	for {
		<-ticker.C
		log.Println(rand.Int())
	}
}

func demo34() {
	m := map[string]int{
		"a": 1,
		"b": 2,
		"c": 3,
	}
	keys := make([]string, 0, len(m))
	for k, _ := range m {
		keys = append(keys, strings.TrimSpace(k))
	}
	sort.Strings(keys)
	for i, s := range keys {
		fmt.Println(i, s)
	}
}

func demo33() {
	quit := make(chan bool)
	timer := time.NewTimer(3 * time.Second)
	go func() {
		time.Sleep(2 * time.Second)
		select {
		case t := <-timer.C:
			fmt.Println("time:", t.Format(time.DateOnly))
		default:
			fmt.Println("无信号")
		}
		quit <- true
	}()
	time.Sleep(3 * time.Second)
	wasStopped := timer.Stop()
	if wasStopped {
		// Go 1.23 或更高版本会走这条分支
		fmt.Println("定时器未过期，停止成功")
	} else {
		// Go 1.23 以前的版本会走这条分支
		fmt.Println("定时器已经过期并且信号已经发送")
	}

	// 等待退出信号
	<-quit
}

func demo32() {
	ctx, cancelFunc := context.WithDeadline(context.Background(), time.Now().Add(time.Second*3))
	defer cancelFunc()
	go watch1(ctx, "监控1")
	go watch1(ctx, "监控2")
	fmt.Println("现在开始等待5秒,time=", time.Now().Unix())
	time.Sleep(5 * time.Second)

	fmt.Println("等待5秒结束,准备调用cancel()函数，发现两个子协程已经结束了，time=", time.Now().Unix())

}

func watch1(ctx context.Context, name string) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println(name, "收到信号, 监控退出, time = ", time.Now().Unix())
			return
		default:
			fmt.Println(name, "goroutine 监控中, time = ", time.Now().Unix())
			time.Sleep(1 * time.Second)
		}
	}
}

func demo31() {
	timeout, cancelFunc := context.WithTimeout(context.Background(), time.Second*3)
	defer cancelFunc()
	for {
		select {
		case <-timeout.Done():
			fmt.Println("timeout")
			return
		default:
			fmt.Println("waiting...")
			time.Sleep(time.Second * 1)
		}
	}

}

func doRetry() {
	for {
		err := doCallSomething()
		if err != nil {
			log.Println(err)
			if !errors.Is(err, ErrTooManyRequests) {
				return
			}
			time.Sleep(time.Second)
		} else {
			return
		}
	}
}

var ErrTooManyRequests = errors.New("too many requests")

func doCallSomething() error {
	resp, err := http.Get("https://www.google.com")
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode == http.StatusTooManyRequests {
		return ErrTooManyRequests
	}
	return nil
}

type Handler interface {
	Execute(*Data) error
	SetNext(Handler) Handler
	Do(*Data) error
}
type Next struct {
	nextHandler Handler
}

func (n *Next) SetNext(handler Handler) Handler {
	n.nextHandler = handler
	return handler
}

func (n *Next) Execute(data *Data) (err error) {
	if n.nextHandler == nil {
		return nil
	}
	if err := n.nextHandler.Do(data); err != nil {
		return err
	}
	return n.nextHandler.Execute(data)
}

type A struct {
	Next
}

func (m *A) Do(d *Data) (err error) {
	if d.IsADone {
		fmt.Println("A has been done")
		return
	}
	fmt.Println("Deal A")
	d.IsADone = true
	return
}

type B struct {
	Next
}

func (m *B) Do(d *Data) (err error) {
	if d.IsBDone {
		fmt.Println("B has been done")
		return
	}
	fmt.Println("Deal B")
	d.IsBDone = true
	return
}

type C struct {
	Next
}

func (m *C) Do(d *Data) (err error) {
	if d.IsCDone {
		fmt.Println("C has been done")
		return
	}
	fmt.Println("Deal C")
	d.IsCDone = true
	return
}

// StartHandler 不做操作，作为第一个 Handler 向下转发请求
type StartHandler struct {
	Next
}

// Do 空 Handler 的 Do
func (h *StartHandler) Do(d *Data) (err error) {
	// 空 Handler 这里什么也不做，只是载体 do nothing...
	fmt.Println("StartHandler do nothing")
	return
}

type Data struct {
	Name    string
	IsADone bool
	IsBDone bool
	IsCDone bool
}

func demo30() {
	s := StartHandler{}
	s.SetNext(&A{}).SetNext(&B{}).SetNext(&C{}).SetNext(&B{})

	// 执行业务流程中的各个责任点
	data := &Data{Name: "abc"}
	if err := s.Execute(data); err != nil {
		fmt.Println("Error:" + err.Error())
		return
	}
	fmt.Println("Success")

}
func demo29() {
	valueFunc := adder()
	fmt.Println(valueFunc(2))
	fmt.Println(valueFunc(2))
}

func adder() func(int) int {
	sum := 0
	return func(v int) int {
		sum += v
		return sum
	}
}

var num int32

func addNum(i int32) {
	atomic.AddInt32(&num, i)
	time.Sleep(time.Millisecond)
	fmt.Println("now num=", num)
}

func demo28() {
	runTimes := 10000

	for _ = range runTimes {
		addNum(1)
	}
	fmt.Printf("result num=%d\n", num)
}

func server() {
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatal(err)
	}
	defer listener.Close()
	done <- struct{}{}
	conn, err := listener.Accept()
	if err != nil {
		log.Fatal("Server Accept", err)
		os.Exit(1)
	}
	log.Println("Server : Accept one connection")
	date := make([]byte, 1)

	if _, err := conn.Read(date); err != nil {
		log.Fatal("Server Read", err)
	}
	log.Printf("Server : Read date : %v", date)
	err = conn.Close()
	if err != nil {
		return
	}
}
func client() {
	conn, err := net.Dial("tcp", "127.0.0.1:8080")
	if err != nil {
		log.Fatal("Client Dial", err)
	}
	log.Println("Client : ", time.Now(), "writes 1 st byte 'a' to serve ")
	if _, err := conn.Write([]byte("a")); err != nil {
		log.Printf("Client Write:%v", err)
	}
	time.Sleep(time.Second * 5)
	log.Println("Client : ", time.Now(), "writes 2 nd byte 'b' to serve ")
	if _, err := conn.Write([]byte("b")); err != nil {
		log.Printf("Client Write:%v", err)
	}
	time.Sleep(time.Second * 5)

	log.Println("Client:", time.Now(), "writes 3rd byte 'c' to server")
	if _, err := conn.Write([]byte("c")); err != nil {
		log.Printf("Client: %v", err)
	}
}

var done = make(chan struct{})

func demo27() {
	go server()
	<-done

	client()
}

func demo26() {
	inWeek := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
	instr := ""
	fmt.Println("input a char:")
	fmt.Scanf("%s\n", &instr)
	outweek(instr, inWeek)
}

func outweek(instr string, inWeek []string) {
	nextstr := ""
	nextweek := make([]string, 0)
	for _, value := range inWeek {
		index := strings.Index(value, instr)
		if index == 0 {
			nextweek = append(nextweek, value)
		}
	}
	fmt.Printf("%s\n", nextweek[0:])
	if len(nextweek) > 1 {
		fmt.Println("input next char:")
		fmt.Scanf("%s\n", &nextstr)
		nextstr = instr + nextstr
		outweek(nextstr, nextweek)
	}
}

type Set[K comparable] map[K]struct{}

func (s Set[K]) Add(k K) {
	s[k] = struct{}{}
}
func (s Set[K]) Remove(k K) {
	delete(s, k)
}
func (s Set[K]) Contains(k K) bool {
	_, ok := s[k]
	return ok
}

func demo25() {
	ch := make(chan int)
	for i := 0; i < 10; i++ {
		go func(i int) {
			ch <- i
		}(i)
	}
	for i := 0; i < 10; i++ {
		fmt.Println(<-ch)
	}
}

func sum(n int) int {
	sum := 0
	for i := 0; i < n; i++ {
		sum += i
	}
	return sum
}

func demo24() {
	n := 1000
	ch := make(chan int)
	for i := 0; i < 10; i++ {
		go func() {
			ch <- sum(n)
		}()
	}
	for i := 0; i < 10; i++ {
		fmt.Println(<-ch)
	}
}

func demo23() {
	datetime := time.Now().Format("2006-01-02 15:04:05")
	fmt.Println(datetime)
	f := func() {
		panic("has error")
	}
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
		}
	}()
	f()
}

func demo22() {
	s := "hêllo"
	fmt.Println(strings.Clone(s[:3]))
	for i, v := range s {
		fmt.Printf("position %d: %c\n", i, v)
	}
	runes := []rune(s)
	for i := range runes {
		fmt.Printf("position %d: %c\n", i, runes[i])
	}
}

func demo21() {
	ch1 := make(chan int, 1)
	close(ch1)
	for {
		v := <-ch1
		fmt.Println(v)
	}
}

//fmt.Println(ok.SS)
//ok.PrintNum(ok.SS)
//wg := sync.WaitGroup{}
//var v uint64
//wg.Add(3)
//for i := 0; i < 3; i++ {
//	go func() {
//		//wg.Add(1)
//		atomic.AddUint64(&v, 1)
//		wg.Done()
//	}()
//}
//wg.Wait()
//fmt.Println(v)

type Person2 struct {
	name string
}

func demo19() {
	personMap := make(map[string]*Person2)
	persons := []Person2{
		{name: "a"},
		{name: "b"},
		{name: "c"},
	}
	for _, v := range persons {
		personMap[v.name] = &v
	}
	for k, v := range personMap {
		fmt.Println(k, "=", v.name)
	}
}

func demo18() {
	var val int64 = 4
	var i interface{} = val
	if newVal, ok := i.(int32); !ok {
		fmt.Println("is not of type int32", ok, newVal)
	} else {
		fmt.Println(newVal)
	}
}

func demo17() {
	ch := make(chan int)
	go func() {
		ch <- 1
	}()
	go func() {
		<-ch
	}()
}

func demo16() {
	m1 := make(map[string]int, 5)
	m1["a"] = 1
	m2 := map[string]int{"foo": 1, "bar": 2}
	delete(m2, "foo")
	for k, v := range m2 {
		fmt.Println(k, v)
	}
	if _, ok := m2["a"]; !ok {
		fmt.Println("key not found")
	}
}

func demo15() {
	var wg sync.WaitGroup
	wg.Add(4)
	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		defer wg.Done()
		watchDog1(ctx, "[监控狗 1 ]")
	}()
	go func() {
		defer wg.Done()
		watchDog1(ctx, "[监控狗 2 ]")
	}()
	go func() {
		defer wg.Done()
		watchDog1(ctx, "[监控狗 3 ]")
	}()

	valCtx := context.WithValue(ctx, "userId", 2)
	go func() {
		defer wg.Done()
		getUser(valCtx)
	}()

	time.Sleep(time.Second * 3)
	cancel()
	wg.Wait()
}

func getUser(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("[获取用户]", "协程退出")
			return
		default:
			userId := ctx.Value("userId")
			fmt.Println("[获取用户]", "用户 ID 为: ", userId)
		}
		time.Sleep(time.Second)
	}
}

func watchDog1(ctx context.Context, name string) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println(name, " 停止指令已收到，马上停止")
			return
		default:
			fmt.Println(name, "正在监控...")

		}
		time.Sleep(time.Second)
	}
}

type BytePoolCap struct {
	c    chan []byte
	w    int
	wcap int
}

func (bp *BytePoolCap) Get() (b []byte) {
	select {
	case b = <-bp.c:
	default:
		if bp.wcap > 0 {
			b = make([]byte, bp.w, bp.wcap)
		} else {
			b = make([]byte, bp.w)
		}
	}
	return
}

func (bp *BytePoolCap) Put(b []byte) {
	select {
	case bp.c <- b:
	default:
		//
	}
}

func demo14() {
	var intP *int = new(int)
	*intP = 1
	fmt.Println(*intP)
	var a int32 = 1
	fmt.Println(string(a))
}

func handleError(err error) string {
	if errs, ok := err.(validator.ValidationErrors); ok {
		var errMsg []string
		for _, fieldError := range errs {
			errMsg = append(errMsg, fmt.Sprintf("Field error: %s, %s", fieldError.Field(), fieldError.Tag()))
		}
		return strings.Join(errMsg, ",")
	}
	return err.Error()
}

type User struct {
	Name  string `json:"name" binding:"required" validate:"min=3,max=20"`
	Age   int    `json:"age" binding:"required" validate:"min=1,max=100"`
	Email string `json:"email" binding:"required" validate:"email"`
}

func isValidUsername(fl validator.FieldLevel) bool {
	username := fl.Field().String()
	for _, char := range username {
		if !unicode.IsLetter(char) && !unicode.IsDigit(char) {
			return false
		}
	}
	return true
}

type CustomValidator struct {
	validator *validator.Validate
}

func (cv *CustomValidator) ValidateStruct(obj interface{}) error {
	if err := cv.validator.Struct(obj); err != nil {
		return err
	}
	return nil
}

func demo13() {
	route := gin.Default()
	route.Use(func(c *gin.Context) {
		cv := &CustomValidator{validator: validator.New()}
		c.Set("validator", cv)
	})
	validate := validator.New()
	err := validate.RegisterValidation("username", isValidUsername)
	if err != nil {
		log.Println("err:", err)
	}

	route.POST("/user", func(c *gin.Context) {
		var user User
		if err := c.ShouldBind(&user); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}
		if v, ok := c.MustGet("validator").(*CustomValidator); ok {
			if err := v.ValidateStruct(user); err != nil {
				c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
				return
			}
		}
		c.JSON(http.StatusOK, gin.H{"message": "user created successfully",
			"user": user})
	})
}

func demo12() {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")
	if err := viper.ReadInConfig(); err != nil {
		fmt.Println("Error reading config file, ", err)
	}
	fmt.Printf("server port:%d\n", viper.GetInt("server.port"))
	fmt.Printf("database host:%s\n", viper.GetString("database.host"))
	fmt.Printf("database user:%s\n", viper.GetString("database.user"))

	viper.SetDefault("server.ip", "127.0.0.1")
	viper.Set("server.name", "nacos")
}

func demo11() {
	http.HandleFunc("/post", func(w http.ResponseWriter, r *http.Request) {
		c, err := r.Cookie("ClientCookieID")
		if err != nil {
			log.Println(err)
		}
		if c != nil {
			w.Write([]byte(c.Value))
			return
		}
		http.SetCookie(w, &http.Cookie{
			Name:    "ClientCookieID",
			Value:   "123456",
			Expires: time.Now().AddDate(1, 0, 0),
		})
		w.Write([]byte("this is cookie \n"))
	})
	log.Fatal(http.ListenAndServe(":8080", nil))

}

func demo10() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	var wg sync.WaitGroup
	wg.Add(1000)
	for i := 0; i < 1000; i++ {
		go worker1(ctx, &wg, i)
	}
	wg.Wait()
}

func worker1(ctx context.Context, wg *sync.WaitGroup, id int) {
	defer wg.Done()
	select {
	case <-time.After(time.Second):
		fmt.Printf("执行完成 %d\n\n", id)
	case <-ctx.Done():
		fmt.Printf("请求超时%d\n", id)
	}
}

type Reader interface {
	Read(p []byte) (n int, err error)
}

type Writer interface {
	Write(p []byte) (n int, err error)
}

type ReadWrite interface {
	Reader
	Writer
}

type File1 struct {
	Name string `json:"name"`
}

func (f *File1) Read(p []byte) (n int, err error) {
	return len(p), nil
}
func (f *File1) Write(p []byte) (n int, err error) {
	return len(p), nil
}

func demo9() {
	file := &File1{Name: "/data/yzp.txt"}
	var rw ReadWrite
	rw = file
	buf := make([]byte, 10)
	n, err := rw.Read(buf)
	if err != nil {
		fmt.Println("Read error: ", err)
	}
	fmt.Printf("Read %d bytes\n", n)
	data := []byte("Hello world")
	n, err = rw.Write(data)
	if err != nil {
		fmt.Println("Write error: ", err)
	}
	fmt.Printf("Write %d bytes\n", n)
}

func PrintAll(vals []interface{}) {
	for _, val := range vals {
		fmt.Println(val)
	}
}

func PrintAll2[T any](vals []T) {
	for _, val := range vals {
		fmt.Println(val)
	}
}

func demo8() {
	intSlice := []int{1, 2, 3, 4, 5}
	fmt.Println("intSlice:", intSlice)
	fmt.Println("reverse intSlice", Reverse(intSlice))
}

func Reverse[T any](s []T) []T {
	for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
		s[i], s[j] = s[j], s[i]
	}
	return s
}

func SumIntOrFloat[K comparable, V VType](m map[K]V) V {
	var s V
	for _, v := range m {
		s += v
	}
	fmt.Println(s)
	return s
}

func SumFloats(m map[string]float64) float64 {
	var s float64
	for _, v := range m {
		s += v
	}
	return s
}

func SumInts(m map[string]int) int {
	var s int
	for _, v := range m {
		s += v
	}
	return s
}

type VType interface {
	int | float64
}

type Config struct {
	Field1 string `json:"field1"`
	Field2 string `json:"field2"`
}

func LoadConfig(config *Config) {
	v := reflect.ValueOf(config).Elem()
	t := v.Type()
	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		jsonTag := field.Tag.Get("json")
		fmt.Println(jsonTag, field.Name)
	}
}

func demo7() {
	LoadConfig(&Config{Field1: "haha", Field2: "yzp"})
}

type Struct2 struct {
	Name string
}

func (s *Struct2) Talk() {
	fmt.Println("Hi,my name is", s.Name)
}

func demo6() {
	instance := &Struct2{Name: "yzp"}
	value := reflect.ValueOf(instance)
	value.MethodByName("Talk").Call(nil)
}

func demo5() {
	x := 3.4
	fmt.Println("type:", reflect.TypeOf(x))
}

type Interface interface {
	DoSomething()
}

type Struct1 struct {
	Name string
}

func (receiver Struct1) DoSomething() {
	fmt.Println()
}
func demo4() {
	struct1 := Struct1{Name: "sdf"}
	DynamicImplementor(struct1)
}
func JSONToStruct(jsonStr []byte, structPtr interface{}) error {
	err := json.Unmarshal(jsonStr, structPtr)
	return err
}

func DynamicImplementor(obj interface{}) Interface {
	val := reflect.ValueOf(obj)
	if val.Kind() != reflect.Struct {
		panic("Object must be a struct")
	}
	fmt.Println("已实现 Interface 接口")
	return obj.(Interface)
}

func demo3() {
	type MyStruct struct {
		Name string
		Age  int
	}
	var myStruct MyStruct
	myStruct.Age = 12
	myStruct.Name = "yzp"
	typeOf := reflect.TypeOf(myStruct)
	valOf := reflect.ValueOf(myStruct)
	fmt.Printf("typeOf:%v, valOf:%v\n", typeOf, valOf)
}

func demo2() {
	ctx, cancelFunc := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancelFunc()
	go func() {
		time.Sleep(1 * time.Second)
		cancelFunc()
	}()
	select {
	case <-ctx.Done():
		fmt.Println("操作已超时")
	case <-time.After(10 * time.Second):
		fmt.Println("操作已完成")
	}
}

func demo1() {
	ctx, cancelFunc := context.WithCancel(context.Background())
	go Working(ctx)
	time.Sleep(3 * time.Second)
	cancelFunc()
	time.Sleep(1 * time.Second)
}

func Working(ctx context.Context) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("下班了")
			return
		default:
			fmt.Println("我正在工作")
			time.Sleep(1 * time.Second)
		}
	}
}

type key int

const (
	requestIDKey key = iota
)

func WithRequestId(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		requestID := r.Header.Get("X-Request-ID")
		ctx := context.WithValue(r.Context(), requestIDKey, requestID)
		r = r.WithContext(ctx)
		next.ServeHTTP(w, r)
	})
}
